package com.erlin.store.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.erlin.common.exception.ElException;
import com.erlin.common.service.BaseService;
import com.erlin.common.utils.JwtTokenUtils;
import com.erlin.common.utils.MessageUtils;
import com.erlin.platform.controller.param.AuditStoreParam;
import com.erlin.platform.entity.ElUser;
import com.erlin.platform.service.IElUserService;
import com.erlin.store.constant.StoreConstant;
import com.erlin.store.controller.param.StoreRegisterParam;
import com.erlin.store.controller.vo.StoreInfoVo;
import com.erlin.store.entity.Store;
import com.erlin.store.mapper.StoreMapper;
import com.erlin.store.service.IStoreService;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author alin
 * @since 2021-05-25
 */
@Service
public class StoreServiceImpl extends ServiceImpl<StoreMapper, Store> implements IStoreService, BaseService {
    private final String phonePattern = "^1[3456789]d{9}$";
    @Autowired
    private IElUserService elUserService;

    @Override
    @Transactional
    public StoreInfoVo register(StoreRegisterParam param) {
        checkRegisterData(param);
        ElUser user = JwtTokenUtils.getCurrentUser();
        Store target = new Store();
        BeanUtils.copyProperties(param, target);
        target.setAuthStatus(StoreConstant.AUTH_STATUS_INREVIEW);
        target.setStoreStatus(StoreConstant.STORE_STATUS_NOTOPEN);
        target.setMid(IdUtil.fastSimpleUUID());
        target.setDirectorId(user.getId());
        target.setDirectorOpenId(user.getOpenId());
        save(target);
        return StoreInfoVo.from(target);
    }

    @Override
    public PageInfo getAuditStore() {
        startPage();
        List<Store> list = list(Wrappers.<Store>lambdaQuery().eq(Store::getAuthStatus, StoreConstant.AUTH_STATUS_INREVIEW));
        List<StoreInfoVo> collect = list.stream().map(StoreInfoVo::from).collect(Collectors.toList());
        return getPageInfo(list,collect);
    }

    @Override
    public boolean auditStore(AuditStoreParam param) {
        Store store = Optional.ofNullable(getOne(Wrappers.<Store>lambdaQuery().eq(Store::getMid, param.getStoreMid()))).orElseThrow(() -> new ElException(MessageUtils.getMessage("store.not.exist")));
        if(!Objects.equals(StoreConstant.AUTH_STATUS_INREVIEW,store.getAuthStatus()) || !Objects.equals(StoreConstant.STORE_STATUS_CLOSE,store.getStoreStatus())){
            throw new ElException(MessageUtils.getMessage("store.auth.status.error"));
        }
        store.setAuthStatus(param.getIsPass()?StoreConstant.AUTH_STATUS_PASS:StoreConstant.AUTH_STATUS_REJECT);
        store.setAuditFailedReason(param.getRejectReason());
        return updateById(store);
    }

    @Override
    public List<StoreInfoVo> searchOwnerStores() {
        ElUser user = JwtTokenUtils.getCurrentUser();
        return Optional.ofNullable(list(Wrappers.<Store>lambdaQuery()
                .eq(Store::getDirectorId,user.getId())
                .eq(Store::getDirectorOpenId,user.getOpenId()))).orElse(Collections.emptyList())
                .stream()
                .map(StoreInfoVo::from)
                .collect(Collectors.toList());
    }

    private void checkRegisterData(StoreRegisterParam param) {
        if (StringUtils.isEmpty(param.getStoreLogo())) {
            param.setStoreLogo(param.getSignBoardImg());
        }
        if (param.getContactNumber().matches(phonePattern)) {
            throw new ElException(MessageUtils.getMessage("user.phone.error"));
        }
    }
}
